package com.hjf.booking.security.config;

import com.hjf.booking.security.authentication.SelfPasswordEncod;
import com.hjf.booking.security.authentication.SelfUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author hjf
 * @date 2021-03-17 9:22
 */
@Component
public class UsernamePasswordAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    SelfUserService selfUserService;

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(UsernamePasswordAuthenticationToken.class);
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        if(username == null || password==null){
            throw new BadCredentialsException("用户名，密码不能为空");
        }
        try {
            UserDetails userDetails = selfUserService.loadUserByUsername(username);
            if(userDetails == null){
                throw new UsernameNotFoundException("用户名不存在");
            }
            if(!SelfPasswordEncod.encode(password).equals(userDetails.getPassword())){
                throw new BadCredentialsException("用户名或密码错误，请核对后重试");
            }
        }catch (UsernameNotFoundException e){
            throw new UsernameNotFoundException("用户名不存在");
        }


        return authentication;
    }
}
